package com.uestc.util;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Random;

import org.springframework.web.multipart.MultipartFile;

import com.uestc.entity.Host;
import com.uestc.util.date.DateStyle;
import com.uestc.util.date.DateUtil;

public class HttpUtil {

	/**
	 * 存文件
	 * 
	 * @param img
	 * @return
	 */
	public static String saveFile(MultipartFile file, Host mHost) {
		return saveFileOrImage(file, mHost.getFile(), mHost.getFileUrl());
	}

	private static String saveFileOrImage(MultipartFile file, String path, String url) {
		if (file==null||file.isEmpty()) {
			return null;
		}
		String originalFilename = file.getOriginalFilename();
		int size = (int) file.getSize();
		System.out.println(originalFilename + "-->" + size);
		String ymd = DateUtil.DateToString(new Date(), DateStyle.YYYYMMDD);
		String fileName = DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS_ME) + new Random().nextInt(10)
				+ getExtName(originalFilename, ".".toCharArray()[0]);
		String pathActual = path + ymd + "/" + originalFilename;
		File dest = new File(pathActual);
		String finalPath=ymd + "/" + originalFilename;
		if (!dest.getParentFile().exists()) { // 判断文件父目录是否存在
			dest.getParentFile().mkdirs();
		}
		// 判断文件是否重复名
		if (dest.exists()) {
			pathActual = path + ymd + "/" + fileName;
			finalPath=ymd + "/" + fileName;
			dest = new File(pathActual);
		}
		try {
			file.transferTo(dest);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return url + finalPath;
	}

	/**
	 * 存图片
	 * 
	 * @param img
	 * @return
	 */
	public static String saveImage(MultipartFile file, Host mHost) {
		return saveFileOrImage(file, mHost.getImage(), mHost.getImageUrl());
	}

	// 取后缀
	public static String getExtName(String s, char split) {
		int i = s.indexOf(split);
		int leg = s.length();
		return (i > 0 ? (i + 1) == leg ? " " : s.substring(i, s.length()) : " ");
	}

	public static void main(String[] args) {
		System.out.println(getExtName("sss.mp3", ".".toCharArray()[0]));
	}
}
